package com.example.forum.service.imp;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.mapper.ArticleReplyMapper;
import com.example.forum.model.ArticleReply;
import com.example.forum.service.IArticleReplyService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServicImp implements IArticleReplyService {

    @Autowired
    private ArticleReplyMapper articleReplyMapper;
    @Autowired
    private ArticleServiceImp articleServiceImp;
    @Override
    public void create(ArticleReply articleReply) {
        if (articleReply == null || articleReply.getArticleId() == null

                || articleReply.getPostUserId() == null

                || StringUtil.isEmpty(articleReply.getContent())) {

            // 打印日志

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            // 抛出异常

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));

        }

       // 设置默认值

        articleReply.setReplyId(null);

        articleReply.setReplyUserId(null);

        articleReply.setLikeCount(0);

        articleReply.setState((byte) 0);

        articleReply.setDeleteState((byte) 0);

        Date date = new Date();

        articleReply.setCreateTime(date);

        articleReply.setUpdateTime(date);

        // 写入数据库

        int row = articleReplyMapper.insertSelective(articleReply);

        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        articleServiceImp.addOneReplyCountById(articleReply.getArticleId());
        // 打印日志
        log.info("回复成功, article id = " + articleReply.getArticleId() + ", user id = " +
                articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //进行参数的验证
        if(articleId == null || articleId <= 0){

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用mapper获取回复列表
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        //返回数据给控制层
        return articleReplies;

    }
}
